package vip.meeet.concurrent;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

public class StopTest3 {
    
    static Object lock = new Object();
    
    public static void main(String[] args) {
        User u1 = new User();
        u1.setId(1);
        u1.setAmount(new BigDecimal(1000));
        User u2 = new User();
        u2.setId(2);
        u2.setAmount(new BigDecimal(0));
        System.out.println(u1);
        System.out.println(u2);
        BigDecimal changeAmount = new BigDecimal(500);
        Change change = new Change(u1,u2,changeAmount);
        change.start();
        try {
            Thread.sleep(1000);//让change线程执行1秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        change.stop();
        change.interrupt();
        try {
            change.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(u1);
        System.out.println(u2);
    }
    
    static class Change extends Thread{
        private User u1,u2;
        private BigDecimal change;
        
        Change(User u1,User u2,BigDecimal change){
            this.u1 = u1;
            this.u2 = u2;
            this.change = change;
        }
        @Override
        public void run() {
            boolean interrupted = false;
            while(!interrupted){
            synchronized(lock){
                BigDecimal subResult = u1.amount.subtract(change);
                u1.setAmount(subResult);
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName() + "线程中断！");
                    interrupted = true;
                }
                BigDecimal addResult = u2.amount.add(change);
                u2.setAmount(addResult);
            }
            }
        }
    }
    
    static class User{
        private int id;
        
        private BigDecimal amount;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public BigDecimal getAmount() {
            return amount;
        }

        public void setAmount(BigDecimal amount) {
            this.amount = amount;
        }

        @Override
        public String toString() {
            return "User [id=" + id + ", amount=" + amount + "]";
        }
        
    }

}
